import axios from 'axios';
import store from '@/store';
import router from '@/router';
import setting from '@/config/setting';
import { MessageBox } from 'element-ui';

// 创建 axios 实例
const http = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  // withCredentials: true // 若需发送 cookie，可开启
});

// 请求拦截器
http.interceptors.request.use((config) => {
  const token = setting.takeToken();
  if (token) {
    config.headers[setting.tokenHeaderName] = token;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// 响应拦截器
http.interceptors.response.use((res) => {
  if (res.data.code === 401) {
    if (res.config.url === setting.menuUrl) {
      goLogin();
    } else {
      MessageBox.alert('登录状态已过期, 请退出重新登录!', '系统提示', {
        confirmButtonText: '重新登录',
        callback: (action) => {
          if (action === 'confirm') {
            goLogin(true);
          }
        },
        beforeClose: () => {
          MessageBox.close();
        }
      });
    }
    return Promise.reject(new Error(res.data.msg));
  }

  const access_token = res.headers[setting.tokenHeaderName];
  if (access_token) {
    setting.cacheToken(access_token);
  }

  return res.data;
}, (error) => {
  return Promise.reject(error);
});

// 跳转到登录页
function goLogin(reload) {
  store.dispatch('user/removeToken').then(() => {
    if (reload) {
      location.replace('/login');
    } else {
      const path = router.currentRoute.path;
      router.push({
        path: '/login',
        query: path && path !== '/' ? { form: path } : null
      });
    }
  });
}

// 构造函数对象 request，等价于 axios.request
const request = (config) => http.request(config);

// 添加常用方法
request.get = (url, params = {}, config = {}) =>
  http.get(url, { params, ...config });

request.post = (url, data = {}, config = {}) =>
  http.post(url, data, config);

request.put = (url, data = {}, config = {}) =>
  http.put(url, data, config);

request.delete = (url, config = {}) =>
  http.delete(url, config);

// 可选：导出原始 axios 实例
request.instance = http;

export default request;



/**
 *
 * 使用示例
 import request from '@/libs/request';

export default {
  methods: {
    async fetchTypeHeader() {
      const res = await request({
        url: '/product/product/type_header',
        method: 'get',
        params: { page: 1 }
      });
      console.log('返回数据', res);
    },

    async saveUser() {
      const res = await request.post('/user/save', { name: '张三' });
      console.log('保存成功', res);
    }
  }
};
 */
